package com.adcc.ags.cgw.healthcheck;

import com.adcc.ags.cgw.entity.mq.MQState;
import com.adcc.ags.cgw.proxy.AMQSProxy;
import com.adcc.utility.log.Log;
import com.codahale.metrics.health.HealthCheck;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;

import java.util.Map;

/**
 * 下行状态监控
 */
public class AMQSHealthCheck extends HealthCheck {

    @Override
    protected Result check() {
        try {
            Map<String,Object> map = Maps.newHashMap();
            Map<String,String> mq = Maps.newHashMap();

            // 获取MQ运行状态
            String strHost = AMQSProxy.getInstance().getAMQS().getHost();
            mq.put("host", Strings.nullToEmpty(strHost));
            int intPort = AMQSProxy.getInstance().getAMQS().getPort();
            mq.put("port",(intPort > 0) ? String.valueOf(intPort) : "");
            String strQM = AMQSProxy.getInstance().getAMQS().getQm();
            mq.put("qm",Strings.nullToEmpty(strQM));
            String strChannel = AMQSProxy.getInstance().getAMQS().getChannel();
            mq.put("channel",Strings.nullToEmpty(strChannel));
            MQState state = AMQSProxy.getInstance().getAMQS().getState();
            mq.put("state", state.toString());
            map.put("mq",mq);
            map.put("updateTime",AMQSProxy.getInstance().getAMQS().getUpdateTime());
            if (AMQSProxy.getInstance().getAMQS().getState() == MQState.CONNECTED) {
                return Result.healthy(new ObjectMapper().writeValueAsString(map));
            } else {
                return Result.unhealthy(new ObjectMapper().writeValueAsString(map));
            }
        } catch (Exception ex) {
            Log.error(AMQSHealthCheck.class.getName(), "check() error", ex);
            return Result.unhealthy(ex.fillInStackTrace());
        }
    }
}
